package com.weilele.mvvm.adapter

import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.viewbinding.ViewBinding
import com.weilele.mvvm.utils.activity.findFragment
import com.weilele.mvvm.utils.activity.getActivity
import com.weilele.mvvm.utils.thread.TickTask
import kotlinx.coroutines.CoroutineScope

/**
 * 带有轮询任务的Holder
 */
abstract class MvvmTickTaskHolder<DataType, Binding : ViewBinding?> :
    MvvmHolder<DataType, Binding> {

    constructor(binding: Binding) : super(binding)
    constructor(itemView: View) : super(itemView)

    override fun onViewAttachedToWindow() {
        super.onViewAttachedToWindow()
        tickTask?.start()
    }

    override fun onViewDetachedFromWindow() {
        super.onViewDetachedFromWindow()
        tickTask?.cancel()
    }

    override fun onViewRecycled() {
        super.onViewRecycled()
        cancelTickTask()
    }

    private var tickTask: TickTask? = null

    /**
     * 开始轮询任务
     */
    fun startTickTask(
        time: Long/*轮询的间隔时间*/,
        onThread: Boolean = false,
        lifecycleOwner: LifecycleOwner? = null
    ) {
        if (tickTask?.isRunning == true) {
            return
        }
        if (lifecycleOwner != null) {
            tickTask =
                TickTask.startWithLifecycleOwner(lifecycleOwner, time, onThread, ::onTick)
            return
        }
        //判断fragment
        if (itemView.parent != null) {
            val fragment = (bindingParent ?: itemView).findFragment<Fragment>()
            if (fragment != null) {
                tickTask =
                    TickTask.startWithLifecycleOwner(fragment, time, onThread, ::onTick)
                return
            }
        }
        //判断activity
        val activity = itemView.getActivity()
        if (activity != null) {
            tickTask = TickTask.startWithLifecycleOwner(activity, time, onThread, ::onTick)
            return
        }
        //无生命周期绑定启动
        tickTask = TickTask.start(time, onThread, ::onTick)
    }

    /**
     * 取消轮询任务
     */
    fun cancelTickTask() {
        tickTask?.cancel()
        tickTask = null
    }

    abstract suspend fun onTick(scope: CoroutineScope)
}